package com.xkstream.client.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.kt.BlogInfo;
import com.xkstream.client.entity.kt.CommentInfo;
import com.xkstream.client.entity.kt.CommentListData;
import com.xkstream.client.presenter.kt.MyZoneDetailContract;
import com.xkstream.client.presenter.kt.MyZoneDetailPresenter;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.adapter.CommentAdapter;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LeakUtil;
import com.xkstream.client.videothumbloader.config.DisplayConfig;
import com.xkstream.client.videothumbloader.core.VideoThumbLoader;
import com.xkstream.client.view.CircleImageView;
import com.xkstream.client.view.FlowLayout;
import com.xkstream.client.view.FullyLinearLayoutManager;
import com.zego.zegoliveroom.ZegoLiveRoom;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by xiaoyi on 2017-9-28.
 * 评论详情
 */

public class CommentDetailActivity extends BaseActivity<MyZoneDetailContract.Presenter>
        implements MyZoneDetailContract.View {
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    @BindView(R.id.tvNickname)
    TextView tvNickname;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvContent)
    TextView tvContent;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.llImage)
    FlowLayout llImage;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.tvAgree)
    TextView tvAgree;
    @BindView(R.id.recycler_comment)
    RecyclerView recyclerComment;
    @BindView(R.id.llComment)
    LinearLayout llComment;

    @BindView(R.id.etComment)
    EditText etComment;

    @BindView(R.id.tvSend)
    TextView tvSend;

    @BindView(R.id.tvDelete)
    TextView tvDelete;

    @BindView(R.id.ivCover)
    ImageView ivConver;
    LinearLayoutManager layoutManager;

    List<CommentInfo> mDatas = new ArrayList<>();
    CommentAdapter adapter;

    @BindString(R.string.reply_someone)
    String replySomeone;

    @BindString(R.string.delete_blog)
    String strDelete;

    BlogInfo blog;

    int width;

    CommentInfo commentInfo;

    private boolean showBottom;
    CompositeDisposable disposable;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_comment);
        disposable = new CompositeDisposable();
        ButterKnife.bind(this);
        presenter = new MyZoneDetailPresenter(this);
        blog = getIntent().getParcelableExtra("blog");
        width = DeviceUtils.deviceWidth(this) - DeviceUtils.dp2px(this, 57);
        layoutManager = new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerComment.setLayoutManager(layoutManager);
        recyclerComment.setItemAnimator(new DefaultItemAnimator());
        adapter = new CommentAdapter(this, mDatas);
        recyclerComment.setAdapter(adapter);
        recyclerComment.setNestedScrollingEnabled(false);
        getCommentList();
        showTalk(blog);
        scroll.smoothScrollTo(0, 0);
        adapter.setOnItemClickListener((v, p) -> {
            commentInfo = mDatas.get(p);
            if (commentInfo.getUser_code().equals(Application.getUser().getUser_code())) {
                commentInfo = null;
                return;
            }
            etComment.setHint(String.format(replySomeone, commentInfo.getNickname()));
        });

        if (TextUtils.isEmpty(blog.getContent())) {
            tvContent.setVisibility(View.GONE);
        } else {
            tvContent.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R.id.ivBack, R.id.tvAgree, R.id.tvSend, R.id.tvDelete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvAgree:
                if (TextUtils.isEmpty(blog.getUpvote_id())) {
                    blogUpvote();
                }
                break;
            case R.id.tvSend:
                publishComment();
                break;
            case R.id.tvDelete:
                showExitDialog();
                break;
        }
    }

    private void blogUpvote() {
        Map<String, String> params = new HashMap<>();
        params.put("blog_id", blog.getId());
        params.put("user_code", Application.getUser().getUser_code());
        params.put("is_like", "1");
        presenter.blogUpVote(params);
        tvAgree.setEnabled(false);
        disposable.add(Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((l) -> tvAgree.setEnabled(true)));
    }

    private void publishComment() {
        if (checkInput()) {
            showBottom = true;
            tvSend.setEnabled(false);
            Map<String, String> params = new HashMap<>();
            params.put("blog_id", blog.getId());
            params.put("user_code", Application.getUser().getUser_code());
            params.put("content", etComment.getText().toString());
            if (commentInfo != null) {
                params.put("parent_id", commentInfo.getId());
            }
            params.put("is_anchor", "1");
            presenter.publishComment(params);
            etComment.setText("");
            commentInfo = null;
            etComment.setHint(R.string.hint_comment);
        } else {
            showTopTips(R.string.say_somthing);
        }
    }

    private boolean checkInput() {
        return !TextUtils.isEmpty(etComment.getText().toString().trim());
    }

    private void showTalk(BlogInfo talk) {
        tvContent.setText(talk.getContent());
        tvComment.setText("" + talk.getComment());
        User user = Application.getUser();
        tvNickname.setText(user.getExt_info().getNickname());
        AsyncImage.loadPhoto(this, Application.getUser().getExt_info().getHead_icon(), ivHeader);
        tvTime.setText(talk.getCreate_date());
        if (!TextUtils.isEmpty(user.getAnchor().getZone_img())) {
            AsyncImage.loadPhoto(this, user.getAnchor().getZone_img(), ivConver);
        }
        tvAgree.setText(talk.getUpvote() + "");
        if (talk.getImages() != null) {
            showImage(talk.getImages(), llImage);
        }
        if (talk.getVideos() != null) {
            showVideos(talk.getVideos(), llImage);
        }
        if (!TextUtils.isEmpty(talk.getUpvote_id())) {
            tvAgree.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_agreed
                    , 0, 0, 0);
        }
    }

    private void showVideos(String[] videos, FlowLayout parent) {
        parent.removeAllViews();
        int imgSize = (int) ((width - DeviceUtils.dp2px(this, 10)) / 1.5);
        for (String url : videos) {
            View view = LayoutInflater.from(this).inflate(R.layout.zone_image_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            FlowLayout.LayoutParams params = new RecyclerView.LayoutParams(imgSize, imgSize);
            //AsyncImage.loadPhoto(mContext, url, imageView);
            DisplayConfig config = new DisplayConfig();
            config.loadingResId = R.drawable.default_img;
            config.failedResId = R.drawable.default_img;
            VideoThumbLoader.getInstance().loadThumb(imageView, url, config,
                    (v, b, u) -> {
                        int height = view.getHeight();
                        int width = height * b.getWidth() / b.getHeight();
                        ViewGroup.LayoutParams rlParams = view.getLayoutParams();
                        rlParams.width = width;
                        rlParams.height = height;
                        view.setLayoutParams(rlParams);
                    });

            ImageView play = new ImageView(this);
            play.setImageResource(R.drawable.icon_play);
            RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(imageView.getLayoutParams());
            rlParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            rlParams.width = DeviceUtils.dp2px(this, 30);
            rlParams.height = DeviceUtils.dp2px(this, 30);
            ((RelativeLayout) view).addView(play, rlParams);

            int padding = DeviceUtils.dp2px(this, 5);
            view.setPadding(padding, padding, padding, padding);
            view.setOnClickListener((v) -> {
                Intent intent = new Intent(this, VideoPlayActivity.class);
                intent.putExtra("path", url);
                jumpToActivity(intent);
            });
            parent.addView(view, params);
        }

    }


    private void showImage(String[] urls, FlowLayout parent) {
        parent.removeAllViews();
        switch (urls.length) {
            case 0:
                break;
            case 1:
                showImageOne(urls, parent);
                break;
            case 2:
                showImageTwo(urls, parent);
                break;
            case 3:
                showImageThreeMore(urls, parent);
                break;
            case 4:
                showImageFour(urls, parent);
                break;
            default:
                showImageThreeMore(urls, parent);
                break;
        }
    }

    private void showImageFour(String[] urls, FlowLayout parent) {

        int imgSize = (width - DeviceUtils.dp2px(this, 10)) / 2;
        for (int i = 0; i < urls.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.zone_image_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            FlowLayout.LayoutParams params = new RecyclerView.LayoutParams(imgSize, imgSize);
            AsyncImage.loadPhoto(this, urls[i], imageView);
            int padding = DeviceUtils.dp2px(this, 5);
            view.setPadding(padding, padding, padding, padding);
            parent.addView(view, params);

            int finalI = i;
            view.setOnClickListener((v) -> {
                showImages(finalI);
            });
        }

    }


    private void showImageOne(String[] urls, FlowLayout parent) {
        int imgSize = (int) ((width - DeviceUtils.dp2px(this, 10)) / 1.5);
        for (String url : urls) {
            View view = LayoutInflater.from(this).inflate(R.layout.zone_image_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
//            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            FlowLayout.LayoutParams params = new RecyclerView.LayoutParams(imgSize, imgSize);
            AsyncImage.loadNetPhotoWithListener(url, imageView, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    super.onLoadingComplete(imageUri, view, loadedImage);
                    int width = imgSize * loadedImage.getWidth() / loadedImage.getHeight();
                    RelativeLayout.LayoutParams viewParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    viewParams.width = width;
                    viewParams.height = imgSize;
                    view.setLayoutParams(viewParams);
                }
            });
            int padding = DeviceUtils.dp2px(this, 5);
            view.setPadding(padding, padding, padding, padding);
            parent.addView(view, params);

            view.setOnClickListener((v) -> {
                showImages(0);
            });
        }
    }

    private void showImageTwo(String[] urls, FlowLayout parent) {

        int imgSize = (width - DeviceUtils.dp2px(this, 10)) / 2;
        for (int i = 0; i < urls.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.zone_image_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            FlowLayout.LayoutParams params = new RecyclerView.LayoutParams(imgSize, imgSize);
            AsyncImage.loadPhoto(this, urls[i], imageView);
            int padding = DeviceUtils.dp2px(this, 5);
            view.setPadding(padding, padding, padding, padding);
            parent.addView(view, params);
            int finalI = i;
            view.setOnClickListener((v) -> {
                showImages(finalI);
            });
        }

    }

    private void showImageThreeMore(String[] urls, FlowLayout parent) {

        int imgSize = (width - DeviceUtils.dp2px(this, 10)) / 3;
        for (int i = 0; i < urls.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.zone_image_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            FlowLayout.LayoutParams params = new RecyclerView.LayoutParams(imgSize, imgSize);
            AsyncImage.loadPhoto(this, urls[i], imageView);
            int padding = DeviceUtils.dp2px(this, 5);
            view.setPadding(padding, padding, padding, padding);
            parent.addView(view, params);
            int finalI = i;
            view.setOnClickListener((v) -> {
                showImages(finalI);
            });
        }

    }

    @Override
    public void showError(@NotNull String message) {
        tvSend.setEnabled(true);
        showTopTips(message);
    }

    @Override
    public void setPresenter(MyZoneDetailContract.Presenter presenter) {
        this.presenter = presenter;
    }

    private void getCommentList() {
        Map<String, String> params = new HashMap<>();
        params.put("blog_id", blog.getId());
        params.put("page_size", "100");
        presenter.getCommentList(params);

    }

    @Override
    public void showCommentResult(@NotNull BaseData<Object> data) {
        tvSend.setEnabled(true);
        if (data.getCode() == 1) {
            showTopTips(R.string.send_success);
            getCommentList();
            blog.setComment(blog.getComment() + 1);
            tvComment.setText(blog.getComment() + "");
            Rxbus.getDefault().post(blog);
        } else {
            showTopTips(data.getMsg());
        }
    }


    @Override
    public void commentList(@NotNull BaseData<CommentListData> t) {
        tvSend.setEnabled(true);
        mDatas.clear();
        if (t.getData() != null) {
            CommentListData data = t.getData();
            if (data != null && data.getList() != null) {
                mDatas.addAll(data.getList());
                adapter.notifyDataSetChanged();
                /*recyclerComment.post(() -> {
                    // scroll.scrollTo(0, scroll.getHeight());
                    if (showBottom) {
                        scroll.fullScroll(ScrollView.FOCUS_UP);
                    }
                });*/
            }
        }
        if (mDatas.size() > 0) {
            llComment.setVisibility(View.VISIBLE);
        } else {
            llComment.setVisibility(View.GONE);
        }
    }

    @Override
    public void showUpVoteResult(@NotNull BaseData<Object> t) {
        if (t.getCode() == 1) {
            showTopTips(R.string.upvote_success);
            blog.setUpvote_id("1");
            blog.setUpvote(blog.getUpvote() + 1);
            tvAgree.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_agreed,
                    0, 0, 0);
            tvAgree.setText(String.valueOf(blog.getUpvote()));
            Rxbus.getDefault().post(blog);
        } else {
            showTopTips(t.getMsg());
        }
    }

    private void showImages(int index) {
        String[] images = blog.getImages();
        Intent intent = new Intent(this, ShowImagesActivity.class);
        intent.putExtra("index", index);
        intent.putExtra("images", images);
        jumpToActivity(intent);
    }

    private void deleteBlog() {
        BlogInfo blogInfo = blog;
        Map<String, String> params = new HashMap<>();
        params.put("user_code", Application.getUser().getUser_code());
        params.put("id", blogInfo.getId());
        presenter.deleteBlog(params);
    }

    private void showExitDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(strDelete);
        dialog.setListener(() -> {
            deleteBlog();
        });
        dialog.show();
    }

    @Override
    public void showDeleteBlogResult(@NotNull BaseData<Object> t) {
        if (t.getCode() == 1) {
            blog.setDelete(true);
            Rxbus.getDefault().post(blog);
            showTopTips(R.string.delete_success);
            disposable.add(Observable.timer(2, TimeUnit.SECONDS)
                    .subscribe((time) -> {
                        finish();
                    }));
            showTopTips(R.string.delete_success);
        } else {
            showTopTips(t.getMsg());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.clear();
        LeakUtil.fixInputMethodManagerLeak(this);
    }
}
